#include "threadpool.h"
#include <unistd.h>
#include <stdatomic.h>
#include <string.h>

typedef struct ARG_PTR
{
    int id;
    int *malptr;
    ThreadPool *pool;
}ARG_PTR;


atomic_int g_count = ATOMIC_VAR_INIT(0);

void taskFunc(void* arg)
{
    int* num = (int*)arg;
    printf("thread %ld is working, number = %d\n",pthread_self(), *num);
    atomic_fetch_add_explicit(&g_count,1,memory_order_relaxed);
}

void* producer(void *arg)
{
    Task task;
    ARG_PTR* agp = (ARG_PTR*)arg;

    for (size_t i = 0; i < 10; i++)
    {
        int c = agp->id * 10 + i + 1;
        memcpy(&agp->malptr[i],&c,sizeof(int));
        
        task.function = taskFunc;
        task.arg = &agp->malptr[i];

        ThreadPollPostTask(agp->pool, &task);
    }
    return arg;
}

int main()
{
    ARG_PTR agp[5] = {0};
    ThreadPool* pool = createThreadPool(10,50);
    
    pthread_t prodecers[5] = {0};
    for (size_t i = 0; i < 5; i++)
    {
        agp[i].pool = pool;
        agp[i].id = i;
        agp[i].malptr = (int*)malloc(sizeof(int) * 10);
        pthread_create(&prodecers[i],NULL,producer,(void*)&agp[i]);
    }

    for (size_t i = 0; i < 5; i++)
    {
        pthread_join(prodecers[i],NULL);
    }
    
    while (g_count < 50)
    {
        sleep(1);
    }

    for (size_t i = 0; i < 5; i++)
    {
        free(agp[i].malptr);
    }

    printf("All tasks completed. Total tasks executed: %d\n",g_count);

    return 0;
}